package com.ve.c51;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.ve.bluetooth.BluetoothSerialAdapter;
import com.ve.bluetooth.BluetoothService;
import com.ve.bluetooth.BluetoothStatus;
import com.ve.compiler.ProgressListener;
import com.ve.downloader.BufferSerial;
import com.ve.downloader.Programmer;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class DownloadActivity extends AppCompatActivity implements ProgressListener {
    private String filePath;
    private TextView fileView, targetView;
    private TextView log;
    private RadioGroup radioGroup;
    private BufferSerial target;
    private Programmer programmer;
    private ExecutorService executorService;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_download);
        fileView = findViewById(R.id.activity_download_file);
        targetView = findViewById(R.id.activity_download_target);
        log = findViewById(R.id.activity_download_log);
        radioGroup = findViewById(R.id.activity_download_target_type);

        executorService = Executors.newSingleThreadExecutor();

        filePath = getIntent().getStringExtra("filePath");
        fileView.setText(filePath);

        EventBus.getDefault().register(this);

        BluetoothService.getDefaultInstance().disconnect();

    }

    public static void start(Context context, String filePath) {
        Intent intent = new Intent(context, DownloadActivity.class);
        intent.putExtra("filePath", filePath);
        context.startActivity(intent);
    }

    @Subscribe
    public void onTargetGet(BufferSerial serial) {
        this.target = serial;
        targetView.setText(target.getName());
    }
    @Subscribe
    public void onFileGet(String file) {
        this.filePath = file;
        fileView.setText(filePath);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (target != null) {
            target.close();
        }
        EventBus.getDefault().unregister(this);
    }

    public void onBackClick(View view) {
        onBackPressed();
    }

    public void onSelectFileClick(View view) {
        startActivity(new Intent(this,SelectFileActivity.class));

    }
    public void onSelectTargetClick(View view) {
        SelectTargetActivity.start(this, radioGroup.getCheckedRadioButtonId() == R.id.activity_download_radio_wire);

    }

    public void onDownloadClick(View view) {

        if (filePath == null) {
            Toast.makeText(this, "请选择下载文件", Toast.LENGTH_SHORT).show();
            return;
        }
        if (target == null) {
            Toast.makeText(this, "请选择目标", Toast.LENGTH_SHORT).show();
            return;
        }
        target.setBaudrate(9600);
        programmer = new Programmer(target);
        programmer.setBluetoothMode(target.isBluetooth());
        programmer.setProgramListener(this::onProgressInfo);
        DownloadActivity progressListener = this;
        executorService.execute(() -> {

            progressListener.onProgress("下载中,请重启单片机");
            try {
                programmer.downloadHex(filePath);

            } catch (Exception e) {
                e.printStackTrace();
                progressListener.onFail("下载失败"+e, e);
                runOnUiThread(() -> {
                    target.close();
                    target=null;
                    targetView.setText("");
                });

            }

        });
    }

    private void println(String info) {
        runOnUiThread(() -> {
            log.append(info + "\n");
        });
    }

    @Override
    public void onSucceed(String info) {
        println(info);
    }

    @Override
    public void onFail(String reason, Exception e) {
        println(reason);
    }

    @Override
    public void onProgress(String detail) {
        println(detail);
    }

    public void onProgressInfo(String detail) {
        println(detail);
    }


}
